<template>
  <div class="login" @mousedown="openFull" @touchstart="openFull">
    <div class="loginNoticeContainers ">
      <div class="loginNotice main-container-content">
        <img v-if="device !== 'mobile'" class="imageCompany" :src="require('@/assets/images/companyTitle.png')" alt="" />
        <div class="loginNoticeRight" @click="showpublishListDialog">
          <img class="imageIcon" :src="require('@/assets/images/loginNoticeTwo.png')" alt="" />
          <span class="imageIconT">公 告/</span>
          <span>Notice</span>
          <el-card class="notice">
            <el-carousel indicator-position="none" arrow="never" direction="vertical" :interval="2000">
              <el-carousel-item v-for="(item, i) in infoList" :key="i" class="notice_item">
                <div class="loginText" @click.stop="showpublishDialog(item)">
                  <span class="b_itemColor0" v-if="item.form == 1">[图文]</span>
                  <span class="b_itemColor1" v-if="item.form == 2">[视频]</span>
                  {{ item.title }}
                </div>
              </el-carousel-item>
            </el-carousel>
          </el-card>
        </div>
      </div>
    </div>

    <div class="loginBg main-container-content">

      <!--   @mousedown="onMouseDown($event)"
        @touchstart="onTouchStart"
        @mousemove="onMouseMove($event)"
        @touchmove="onTouchMove" -->
      <el-row :gutter="10">
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
         <!--  :class="device == 'mobile' ? 'active' : ''" -->

          <div ref="refLogin">
            <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" :class="{'active':device == 'mobile','active1':!radioDeptIdStatus}"
              label-width="54px" label-position="left">
              <!--                <div class="title">{{ title }}</div>-->
              <!--                <div class="engTitle">WELCOME TO SYSTEM</div>-->
              <!-- @focus="openFull" -->
              <div class="loginFormTitle">登录</div>
              <el-form-item prop="username" label="账号">
                <el-input v-model="loginForm.username" type="text" auto-complete="off" clearable placeholder="账号">
                  <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
                </el-input>
              </el-form-item>
              <el-form-item prop="password" label="密码">
                <el-input v-model="loginForm.password" type="password" auto-complete="off" clearable placeholder="密码"
                  @keyup.enter.native="handleLogin">
                  <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
                </el-input>
              </el-form-item>
              <el-form-item prop="code" v-if="captchaEnabled">
                <el-input v-model="loginForm.code" auto-complete="off" placeholder="验证码" style="width: 63%"
                  @keyup.enter.native="handleLogin">
                  <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
                </el-input>
                <div class="login-code">
                  <img :src="codeUrl" @click="getCode" class="login-code-img" />
                </div>
              </el-form-item>
              <!-- @change="changeHospitaldept" -->
              <el-form-item prop="radioDeptId" label="门诊" v-if="radioDeptIdStatus">
                <el-select v-model="loginForm.radioDeptId" filterable placeholder="选择当前坐诊门诊" @change="changeHospitaldept"
                  :disabled="deptIdOptiondisabled">
                  <el-option v-for="item in deptOptionsArr" :key="item.deptId" :label="item.deptName"
                    :value="item.deptId"></el-option>
                </el-select>
              </el-form-item>
              <div style="width: 100%;margin-bottom:10px;">
                <el-button :loading="loading" size="medium" type="primary" style="width: 100%;border-radius: 40px;"
                  @click.native.prevent="handleLogin">
                  <span v-if="!loading">登 录</span>
                  <span v-else>登 录 中...</span>
                </el-button>
                <div style="float: right" v-if="register">
                  <router-link class="link-type" :to="'/register'">立即注册</router-link>
                </div>
              </div>

              <el-checkbox v-model="loginForm.rememberMe" style="margin: 0px 0px 25px 0px">记住密码</el-checkbox>
            </el-form>
          </div>
        </el-col>
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <div class="loginBgRight">
            <div class="title1">医美中心</div>
            <div class="title">全流程业务管理系统</div>
            <div class="engTitle">WELCOME TO THE SYSTEM</div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 通知信息查询-->
    <el-dialog :title="publishTitle" :visible.sync="publishDialog" :width="device !== 'mobile' ? '70%' : '90%'"
      :close-on-click-modal="false" v-dialogDrag>
      <div class="publishTitle">
        {{ publishTitle }}
      </div>
      <div class="publishContent" v-if="publishDialog">
        <div v-html="publishObj.content" v-if="publishObj.form == 1"></div>
        <div v-if="publishObj.form == 2" class="publishVideo">
          <video width="100%" height="100%" controls="controls" :src="publishObj.videoUrl"
            v-if="publishObj.videoUrl"></video>
        </div>
      </div>
    </el-dialog>
    <!-- 信息列表 -->
    <el-dialog title="信息公告" :visible.sync="publishListDialog" :width="device !== 'mobile' ? '70%' : '90%'"
      :close-on-click-modal="false" v-dialogDrag>
      <div id="publishMain1">
        <div class="b_item" v-for="(item, i) in infoList" :key="i" @click="showpublishDialog(item)">
          <p class="p_item" v-if="item.form == 1">
            <span class="b_itemColor0">[图文]</span> {{ item.title }}
          </p>
          <p class="p_item" v-if="item.form == 2">
            <span class="b_itemColor1">[视频]</span> {{ item.title }}
          </p>
        </div>
      </div>
    </el-dialog>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 上海爱可及医疗科技有限公司技术支持</span>
    </div>
    <Screenfull v-show="false" ref="Screenfull"></Screenfull>
  </div>
</template>

<script>
const { body } = document
const WIDTH = 1080 // refer to Bootstrap's responsive design
import {
  infoView,
  getInfoDetail,
  infoRecord,
} from "@/api/infoRelease/infoRelease";
import { getCodeImg } from "@/api/login";
import { deptBuyUsername } from "@/api/system/dept";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import Screenfull from "@/components/Screenfull";
export default {
  name: "Login",
  components: { Screenfull },
  data() {
    return {
      userRole: [],
      deptOptionsArr: [],
      deptIdOptiondisabled: false,
      radioDeptIdStatus: false,
      activeId: 0,
      publishListDialog: false,
      publishTitle: "",
      publishObj: {},
      publishDialog: false,
      title: process.env.VUE_APP_TITLE,
      codeUrl: "",
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: "",
        radioDeptId:'',
      },
      loginRules: {
        username: [
          {
            required: true,
            trigger: "blur",
            message: "请输入您的账号",
          },
        ],
        password: [
          {
            required: true,
            trigger: "blur",
            message: "请输入您的密码",
          },
        ],
        radioDeptId: [
          {
            required: true,
            trigger: "blur",
            message: "请选择坐诊门诊",
          },
        ],
        code: [
          {
            required: true,
            trigger: "change",
            message: "请输入验证码",
          },
        ],
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: false,
      redirect: undefined,
      infoList: [],
      //登陆框可拖拽属性初始化
      startX: 0,
      startY: 0,
      offsetX: 0,
      offsetY: 0,
      isScrolling: false,
      device: '',
      mouse: {
        // 鼠标相关属性
        init: {
          // 鼠标移动前的位置属性, 如果鼠标还未Click过, 则为空
          x: null, // 鼠标x轴定位
          y: null, // 鼠标y轴定位
        },
      },
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
    'loginForm.username': function () {
      this.getDept()
    },
  },
  created() {
    this.$_resizeHandler()
    this.getCode();
    this.getCookie();
    this.getList();

  },
  computed: {

  },
  beforeMount() {
    window.addEventListener('resize', this.$_resizeHandler)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.$_resizeHandler)
  },
  mounted() {
    // let that=this
    // let data=that.dict.type.sys_info_type
    // console.log(data)
    //      if(data&&data.length>0){
    //       that.getList(data[0].value)
    //  }

  },
  methods: {
    getDept() {
      console.log("执行，查找dept")
      let that = this;
      if (that.loginForm.username) {
        let params = {
          username: that.loginForm.username,
        };
        deptBuyUsername(params).then((response) => {
          let data = response.data.deptList
          if (data) {

            that.userRole = response.data.roleIdList
            const foundElement = data.find(item => item.deptId === 100);
            if (that.userRole&&that.userRole.includes(1)) {// 超级管理员  可以不选
              this.$set(that.loginForm, "radioDeptId",  "")
          
            
              that.radioDeptIdStatus = false
            } else if (that.userRole&&that.userRole.includes(2)) {// 医院管理员 不需要选择
              this.$set(that.loginForm, "radioDeptId",  "")
            
              that.radioDeptIdStatus = false
            } else {
              if (foundElement !== undefined) {//平台级账号不需要选择 门诊
                //console.log('数组中包含该元素');
                this.$set(that.loginForm, "radioDeptId",  "")
             
                that.radioDeptIdStatus = false
              } else {  //需要选择门诊
                //console.log('数组中不包含该元素');
                //const filteredArray = array.filter(item => item !== 3); // 过滤掉值为 3 的元素
                let deptOptionsArr = data.filter(item => item.parentId !== 100)
                that.deptOptionsArr = deptOptionsArr
                if (deptOptionsArr) {
                  if (deptOptionsArr.length == 1) {//一个部门默认
                    // that.loginForm.radioDeptId = deptOptionsArr[0].deptId
                    this.$set(that.loginForm, "radioDeptId", deptOptionsArr[0].deptId)
                  
                  } else {// 两个及以上 需要选择
                    const currentDeptId = Cookies.get("currentDeptId");
                    if (currentDeptId) {
                      that.loginForm.radioDeptId =Number(currentDeptId)
                    }else{
                      this.$set(that.loginForm, "radioDeptId",  "")
                    }
                  }
                  that.radioDeptIdStatus = true
                } else {
                 // that.loginForm.radioDeptId =undefined
                 this.$set(that.loginForm, "radioDeptId",  "")
                  that.radioDeptIdStatus = true
                  this.$message.warning("当前账号不存在~，请重新输入")
                }

              }
            }

          } else {
           // that.loginForm.radioDeptId =undefined
            that.radioDeptIdStatus = false
          }
        });

      }
    },
    changeHospitaldept(e) {
     
      if (e) {
       console.log(e)
      //   this.loginForm.radioDeptId=e
      //   console.log( this.loginForm.radioDeptId)
        this.$nextTick(() => {
        this.$forceUpdate()
      })
        // Cookies.set("currentDeptId", e, { expires: 30 });
      }
    

    },
    openFull() {
      if (this.device == 'mobile') {
        this.$refs.Screenfull.open()
      }

    },
    $_isMobile() {
      const rect = body.getBoundingClientRect()
      return rect.width - 1 < WIDTH
    },
    $_resizeHandler() {
      if (!document.hidden) {
        const isMobile = this.$_isMobile()
        //store.dispatch('app/toggleDevice', isMobile ? 'mobile' : 'desktop')
        this.device = isMobile ? 'mobile' : 'desktop'
        console.log(this.device)
      }

    },
    onTouchStart(e) {
      this.startX = e.touches[0].clientX;
      this.startY = e.touches[0].clientY;
      this.offsetX = this.$refs.refLogin.offsetLeft;
      this.offsetY = this.$refs.refLogin.offsetTop;
      this.isScrolling = false;
    },
    onTouchMove(e) {
      const x = e.touches[0].clientX - this.startX + this.offsetX;
      const y = e.touches[0].clientY - this.startY + this.offsetY;
      const maxX = window.innerWidth - this.$refs.refLogin.offsetWidth;
      const maxY = window.innerHeight - this.$refs.refLogin.offsetHeight;
      this.$refs.refLogin.style.left = `${x < 0 ? 0 : x > maxX ? maxX : x}px`;
      this.$refs.refLogin.style.top = `${y < 0 ? 0 : y > maxY ? maxY : y}px`;
      if (
        Math.abs(e.touches[0].clientX - this.startX) > 5 ||
        Math.abs(e.touches[0].clientY - this.startY) > 5
      ) {
        this.isScrolling = true;
      }
    },
    onTouchEnd(e) {
      if (!this.isScrolling) {
        if (e.changedTouches[0].clientX < window.innerWidth / 2) {
          this.$refs.refLogin.style.left = 0;
        } else {
          this.$refs.refLogin.style.left = `${window.innerWidth - this.$refs.refLogin.offsetWidth
            }px`;
        }
      }
    },
    onMouseDown: function (event) {
      // 当鼠标按下某DOM
      this.$refs.refLogin.style.cursor = "move"; // 修改鼠标指针样式
      this.mouse.init.x = event.clientX; // 获取鼠标X轴定位
      this.mouse.init.y = event.clientY; // 获取鼠标Y轴定位
      window.onmouseup = this.onMouseUp; // 设置监听全窗口鼠标弹起事件
      // event.preventDefault(); // 阻止默认事件
    },
    onMouseMove: function (event) {
      if (this.$refs.refLogin.style.cursor != "move") {
        // 如果没有选中的元素
        return; // 立即结束
      }

      let domLeft =
        this.$refs.refLogin.offsetLeft + event.clientX - this.mouse.init.x; // 当前DIV的X轴位置 + 当前鼠标x轴位置 - 鼠标移动前的位置, // 后两者减法计算即为计算鼠标X轴偏移量
      let domTop =
        this.$refs.refLogin.offsetTop + event.clientY - this.mouse.init.y; // 当前DIV的Y轴位置 + 当前鼠标y轴位置 - 鼠标移动前的位置, // 后两者减法计算即为计算鼠标Y轴偏移量
      this.mouse.init.x = event.clientX; // 更新鼠标X轴位置
      this.mouse.init.y = event.clientY; // 更新鼠标Y轴位置
      this.$refs.refLogin.style.left = `${domLeft}px`; // DIV Y轴位置赋值, 即Y轴移动
      this.$refs.refLogin.style.top = `${domTop}px`; // DIV X轴位置赋值, 即X轴移动
    },
    onMouseUp: function (event) {
      // 鼠标左键弹起处理
      this.$refs.refLogin.style.cursor = "default"; // 修改鼠标指针样式// 置空选中元素
      console.log(`鼠标已被放开`);
      window.onmouseup = null;
    },
    showpublishListDialog() {
      if (this.infoList.length > 0) {
        this.publishListDialog = true;
      }
    },
    /** 查询设备列表 */
    getList() {
      let that = this;
      let params = {
        publishLocation: 1,
      };
      infoView(params).then((response) => {
        let data = response.rows;
        this.infoList = data;
      });
    },
    showpublishDialog(item) {
      const infoId = item.infoId;
      getInfoDetail(infoId).then((response) => {
        let data = response.data;
        this.publishObj = data;
        this.publishTitle = data.title;
        this.publishDialog = true;
        this.postinfoRecord(infoId);
      });
    },
    postinfoRecord(id) {
      const infoId = id;
      let params = {
        infoId: id,
      };
      infoRecord(params).then((response) => { });
    },
    getCode() {
      getCodeImg().then((res) => {
        this.captchaEnabled =
          res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get("rememberMe");
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password:
          password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      };
    },
    handleLogin() {
    
      this.openFull()
      console.log("this.loginForm.radioDeptId" + this.loginForm.radioDeptId)
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          if(this.loginForm.radioDeptId){
            Cookies.set("currentDeptId", this.loginForm.radioDeptId, { expires: 30 });
          }else{
            Cookies.remove("currentDeptId");
          }
         
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, {
              expires: 30,
            });
            Cookies.set("password", encrypt(this.loginForm.password), {
              expires: 30,
            });
            Cookies.set("passwordNum", this.loginForm.password, { expires: 30 });
            Cookies.set("rememberMe", this.loginForm.rememberMe, {
              expires: 30,
            });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove("rememberMe");
            Cookies.remove("passwordNum");
          }
          this.$store
            .dispatch("Login", this.loginForm)
            .then(() => {
              this.loading = false;
              console.log('登录成功了---------------------------------')
              this.$router.push({ path: this.redirect || "/" }).catch(() => { });

            })
            .catch(() => {
              console.log("--------");
              this.loading = false;
              if (this.captchaEnabled) {
                this.getCode();
              }
            });
        }
      });
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "~@/assets/styles/common.scss";

.p_item {
  margin: 0px;
  margin-top: 0px !important;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
  color: #333;
}

#publishMain1 {
  max-height: 600px;
  overflow-y: auto;
}

.b_item {
  line-height: 30px;
  margin-bottom: 10px;
  font-size: 18px;

  .b_itemColor0 {
    color: #0256ff;
    margin-right: 5px;
    font-weight: 700;
  }

  .b_itemColor1 {
    color: red;
    margin-right: 5px;
    font-weight: 700;
  }
}

.b_itemColor0 {
  color: #0256ff;
  margin-right: 5px;
  font-weight: 700;
}

.b_itemColor1 {
  color: red;
  margin-right: 5px;
  font-weight: 700;
}

.publishTitle {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  line-height: 30px;
}

.publishContent {
  font-size: 18px;
  line-height: 24px;
  margin-top: 20px;
  max-height: 60vh;
  overflow: hidden;
  overflow-y: auto;

  ::v-deep img {
    max-width: 100% !important;
  }
}

.publishVideo {
  width: 100%;
  height: 400px;
}

.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  //background-image: url("../assets/images/login-background.jpg");
  //background-image: url("../assets/images/loginBg.jpg");
  background-image: url("../assets/images/loginBgTwo.jpg");
  background-size: cover;
}





.loginBg {
  background-size: cover;
  border-radius: 10px;
  margin: 0 auto;
}



//.title {
//    margin-top: 30px;
//    margin-bottom: 20px;
//    text-align: center;
//    font-size: 30px;
//    font-weight: bold;
//    background: linear-gradient(0deg, #2F81ED, #2EE9D8);
//    /*设置线性渐变*/
//    -webkit-background-clip: text;
//    /*背景被裁剪到文字*/
//    -webkit-text-fill-color: transparent;
//    /*设置文字的填充颜色*/
//}
//
//.engTitle {
//    margin-bottom: 80px;
//    text-align: center;
//    font-size: 24px;
//    color: #B4B4B4;
//}



.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  //font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
  margin-bottom: 30px;
}

.login-code-img {
  height: 38px;
}

.el-dialog {
  left: 50% !important;
  transform: translateX(-50%);
}
</style>
